// pages/room5/storyResultPage.js
import room4TestData from "../../testData/testR4Data";
const app = getApp();
var mfApi = require('../../../api/api.js');
let ZW_Ctx = null;
let ZW_Canvas = null;

Page({

        /**
         * 页面的初始数据
         */
        data: {
                inStoryId: "",
                storyDetailData: null,

                baseUrl: app.globalData.baseUrl,
                /**
                 * 房间资源
                 */
                roomResourceData: room4TestData,

                userIcon: app.globalData.userIcon,
                userName: app.globalData.userName,

                certifyImageUrl: "",
                certifyText: "",
                certifyTitle: "",
                certifyQrImage: null,
                joinIndex: '--',
                certifyTextShowNum: '--',

                shotImageUrl: null,

        },

        onShareTimeline:function(){
 
        },
        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: function (options) {
                console.log(options)
                this.setData({
                        inStoryId: options.storyId,
                        // certifyImageUrl: options.selectImageFile,
                        userIcon: app.globalData.userIcon,
                        userName: app.globalData.userName,
                        canvasWidth: 750 * 0.4, // 300
                        canvasHeight: 1624 * 0.4, // 650
                        top: app.menu.top,
                        h: app.menu.height
                })

                //setTimeout(() => {
                        this.getStoryDetail();

                        
                        
                //}, 0);
        },

        onReady() {
                const query = wx.createSelectorQuery()
                query.select('#indexcanvas')
                        .fields({
                                node: true,
                                size: true
                        })
                        .exec((res) => {
                                ZW_Canvas = res[0].node
                                ZW_Ctx = ZW_Canvas.getContext('2d')

                                const dpr = wx.getSystemInfoSync().pixelRatio
                                ZW_Canvas.width = res[0].width * dpr
                                ZW_Canvas.height = res[0].height * dpr
                                ZW_Ctx.scale(dpr, dpr)
                        })
        },

        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onShow: function () {},

        async getStoryDetail() {
                // this.data.inStoryId
                // 1513764683485835266
                let infores = await mfApi.http(mfApi.getStoryById(this.data.inStoryId), "POST");
                // let infores = await mfApi.http(mfApi.getStoryById("1518264171971973121"), "POST");

                if (infores.code != 200) {
                        wx.hideLoading();
                        wx.showToast({
                                icon: "none",
                                title: '后端服务异常',
                        })
                        return;
                }

                this.setData({
                        storyDetailData: infores.result,
                        certifyImageUrl: infores.result.storyImgUrl,
                        certifyText: infores.result.storyDesc,
                        certifyTitle: infores.result.storyTitle,
                        certifyQrImage: null,
                        joinIndex: infores.result.positionNum,
                        certifyTextShowNum: infores.result.storyNum,
                        userIcon: infores.result.avatar,
                        userName: infores.result.nickName,
                });

                console.log('get data');


                        this.drawCanvas();
        },

        async drawCanvas() {
                let _self = this;
                // 获取小程序二维码
                let qrRes = await mfApi.http(mfApi.genQrcode(), "POST", {
                        "auto_color": true,
                        "check_path": false,
                        "env_version": "release",
                        "is_hyaline": false,
                        "page": "pages/index/index",
                        "scene": `storyId//${this.data.inStoryId}`,
                        "width": 500
                })

                console.log(qrRes)
                if (qrRes.code != 200) {
                        wx.showToast({
                                icon: "none",
                                title: '后端服务异常',
                        })
                        return;
                }

                // canvas上的一堆图片
                let imageInfoData = [{
                                des: "用户头像",
                                type: "main",
                                srcUrl: _self.data.userIcon ? _self.data.userIcon : _self.data.baseUrl + '/room5/user.png',
                                posx: 27,
                                posy: 69,
                                width: 48,
                                height: 48,
                                cornerTopLeft: 24,
                                cornerTopRight: 24,
                                cornerBottomLeft: 24,
                                cornerBottomRight: 24,
                        }, {
                                des: "副标题",
                                srcUrl: `${_self.data.baseUrl}/room5/result-title.png`,
                                posx: 54,
                                posy: 139,
                                width: 191,
                                height: 22
                        },
                        {
                                des: "主图",
                                type: "main",
                                scaleNeed: true,
                                srcUrl: `${_self.data.certifyImageUrl}`,
                                posx: 60,
                                posy: 210,
                                width: 180,
                                height: 195,
                                cornerTopLeft: 45,
                                cornerTopRight: 45,
                                cornerBottomLeft: 10,
                                cornerBottomRight: 20,
                        }, {
                                des: "主图外框",
                                srcUrl: `${_self.data.baseUrl}/room5/image-frame.png`,
                                posx: 56,
                                posy: 205,
                                width: 213,
                                height: 257
                        }, {
                                des: "底部外框",
                                srcUrl: `${_self.data.baseUrl}/room5/result-zhengshu-bottom.png`,
                                posx: 0,
                                posy: 557,
                                width: 303,
                                height: 95
                        },
                        {
                                des: "二维码",
                                type: "main",
                                srcUrl: qrRes.result.fileUrl,
                                posx: 222,
                                posy: 566,
                                width: 60,
                                height: 60,
                                cornerTopLeft: 30,
                                cornerTopRight: 30,
                                cornerBottomLeft: 30,
                                cornerBottomRight: 30,
                        }
                ]

                let bgData = {
                        des: "bg",
                        srcUrl: _self.data.baseUrl + _self.data.roomResourceData.showBackgroundImage,
                        posx: 0,
                        posy: 0,
                        width: 350,
                        height: 700
                }

                await this.canvasDrawImage(bgData)

                // ios需要往下挪一点
                let tempS = app.system.system.toLowerCase();
                let isContain = tempS.includes("ios");

                // 证书编号
                ZW_Ctx.font = "9px LaMerHeadlineWhiteItalic";
                let zlen0 = ZW_Ctx.measureText(`NO.${this.data.certifyTextShowNum}`).width;
                ZW_Ctx.font = "9px LaMerHeadlineWhiteItalic";
                ZW_Ctx.fillStyle = "rgb(91, 113, 118)";
                ZW_Ctx.fillText(`NO.${this.data.certifyTextShowNum}`, 300 - (zlen0) - 40, 76);

                // user  白线
                let temp = {
                        des: "底部外框标题",
                        srcUrl: `${_self.data.baseUrl}/room5/story-line.png`,
                        posx: 84,
                        posy: isContain ? 78 : 81,
                        width: 280 - 26 - 26 - 48 - 18 - (zlen0),
                        height: 0.5
                };
                imageInfoData.push(temp);

                // 内容线
                let tempLine = {
                        des: "内容分割线",
                        srcUrl: `${_self.data.baseUrl}/room5/story-line.png`,
                        posx: 55,
                        posy: 462,
                        width: 300 - 110,
                        height: 0.5
                };
                imageInfoData.push(tempLine);

                // 副标题 三段组成
                ZW_Ctx.font = "12px Arial";
                ZW_Ctx.textBaseline = 'top';
                ZW_Ctx.fillStyle = 'rgb(55, 55, 55)';
                let len0 = ZW_Ctx.measureText("感 谢 你 成 为 第").width;
                let len2 = ZW_Ctx.measureText("位 参 展 人").width;

                ZW_Ctx.font = "14px LaMerHeadlineWhiteItalic";
                ZW_Ctx.textBaseline = 'top';
                ZW_Ctx.fillStyle = 'rgb(55, 55, 55)';
                let len1 = ZW_Ctx.measureText(` ${this.data.joinIndex} `).width;

                // part0
                ZW_Ctx.font = "12px Arial";
                ZW_Ctx.fillText("感 谢 你 成 为 第", (300 - (len0 + len1 + len2)) / 2, 173);

                // part2
                ZW_Ctx.fillText("位 参 展 人", ((300 - (len0 + len1 + len2)) / 2) + len0 + len1, 173);

                // part1
                ZW_Ctx.textBaseline = 'top';
                ZW_Ctx.font = "14px LaMerHeadlineWhiteItalic";
                ZW_Ctx.fillStyle = 'rgb(55, 55, 55)';
                ZW_Ctx.fillText(` ${this.data.joinIndex} `, ((300 - (len0 + len1 + len2)) / 2) + len0, 172);

                // userName
                ZW_Ctx.font = "15px Arial";
                ZW_Ctx.fillText(`@${_self.data.userName}`, 85, 87);

                // 故事内容
                let str0 = `《${_self.data.certifyTitle}》`
                let str1 = _self.data.certifyText

                console.log(str0);
                console.log(str1);
                ZW_Ctx.font = "15px Arial";
                ZW_Ctx.textBaseline = 'top';
                ZW_Ctx.fillStyle = 'rgb(0, 0, 0)';
                ZW_Ctx.fillText(str0, 50, 441);

                ZW_Ctx.font = "10px Arial";
                ZW_Ctx.textBaseline = 'top';
                ZW_Ctx.fillStyle = 'rgb(0, 0, 0)';
                ZW_Ctx.fillText(str1, 55, 472);

                // let templeft = {};
                // templeft.srcUrl = _self.data.baseUrl + "/room5/sign-left.png";
                // templeft.posx = contentText0x - 25;
                // templeft.posy = 560;
                // templeft.width = 15;
                // templeft.height = 12;
                // imageInfoData.push(templeft);

                // let tempright = {};
                // tempright.srcUrl = _self.data.baseUrl + "/room5/sign-right.png";
                // tempright.posx = contentText1x - 10;
                // tempright.posy = 570;
                // tempright.width = 15;
                // tempright.height = 12;
                // if (str1.length > 0) {
                //         tempright.posx = contentText1x + str1Width + 10;
                //         tempright.posy = 590;
                // } else {
                //         tempright.posx = contentText0x + str0Width + 10;
                //         tempright.posy = 560;
                // }
                // imageInfoData.push(tempright);

                // {
                //         des: "头像边的白线",
                //         srcUrl: _self.data.baseUrl + '/room5/story-line.png',
                //         posx: 93,
                //         posy: 56,
                //         width: 313,
                //         height: 2
                // },


                for (let i = 0; i < imageInfoData.length; i++) {
                        console.log("draw  image  " + i)
                        let re = null;
                        if (imageInfoData[i].type && imageInfoData[i].type == "main")
                                re = await this.canvasDrawMainImage(imageInfoData[i]);
                        else
                                re = await this.canvasDrawImage(imageInfoData[i])
                        console.log(re)
                }

                let re = await this.shotCanvasImage();
                        if (re.code != 0) {
                            wx.showToast({
                                icon: "none",
                                title: '海报生成失败',
                            })
                            wx.hideLoading();
                            return;
                        }
        },

        canvasDrawImage(imageInfoData) {
                return new Promise(function (resolve, reject) {
                        let tempImage = ZW_Canvas.createImage();
                        tempImage.src = imageInfoData.srcUrl;
                        tempImage.onload = () => {
                                ZW_Ctx.drawImage(tempImage,
                                        imageInfoData.posx,
                                        imageInfoData.posy,
                                        imageInfoData.width,
                                        imageInfoData.height);

                                resolve({
                                        code: 0,
                                })
                        }
                })
        },

        canvasDrawMainImage(imageInfoData) {
                let _self = this;

                return new Promise(function (resolve, reject) {
                        wx.getImageInfo({
                                src: imageInfoData.srcUrl,
                                success(res) {
                                        console.log("getImageInfo === ", res)
                                        let tempImage = ZW_Canvas.createImage();
                                        tempImage.src = imageInfoData.srcUrl;
                                        tempImage.onload = () => {
                                                // res.path;
                                                ZW_Ctx.save();

                                                let w = imageInfoData.width;
                                                let h = imageInfoData.height;
                                                let x = imageInfoData.posx;
                                                let y = imageInfoData.posy;

                                                let r = 20;
                                                if (w < 2 * r) r = w / 2;
                                                if (h < 2 * r) r = h / 2;
                                                ZW_Ctx.beginPath();
                                                ZW_Ctx.moveTo(x + r, y);
                                                ZW_Ctx.arcTo(x + w, y, x + w, y + h, imageInfoData.cornerTopRight);
                                                ZW_Ctx.arcTo(x + w, y + h, x, y + h, imageInfoData.cornerBottomRight);
                                                ZW_Ctx.arcTo(x, y + h, x, y, imageInfoData.cornerBottomLeft);
                                                ZW_Ctx.arcTo(x, y, x + w, y, imageInfoData.cornerTopLeft);

                                                ZW_Ctx.closePath();

                                                ZW_Ctx.clip();


                                                if (imageInfoData.scaleNeed == false) {
                                                        ZW_Ctx.drawImage(tempImage,
                                                                imageInfoData.posx,
                                                                imageInfoData.posy,
                                                                imageInfoData.width,
                                                                imageInfoData.height);
                                                } else {
                                                        let imgX = imageInfoData.posx; //图片在画布上的x轴坐标
                                                        let imgY = imageInfoData.posy; //图片在画布上的y轴坐标
                                                        let imgW = imageInfoData.width; //图片在画布上的宽度
                                                        let imgH = imageInfoData.height; //图片在画布上的高度

                                                        let visibleW = res.width //截取的图片的宽度
                                                        let visibleH = res.height //截取的图片的高度
                                                        let visibleX = null // 所截取的图片的x轴坐标
                                                        let visibleY = null // 所截取的图片的y轴坐标

                                                        let imgBili = imgW / imgH
                                                        let visibleBili = visibleW / visibleH
                                                        if (imgBili < visibleBili) {
                                                                let newW = (imgH / visibleH) * visibleW
                                                                const bili = newW / visibleW
                                                                visibleX = Math.abs(imgW - newW) / 2 / bili
                                                                visibleY = 0
                                                                visibleW = imgW * visibleH / imgH
                                                        } else {
                                                                visibleX = 0
                                                                let newH = (imgW * visibleH) / visibleW
                                                                const bili = newH / visibleH
                                                                visibleY = Math.abs(imgH - newH) / 2 / bili
                                                                visibleH = visibleW * imgH / imgW
                                                        }

                                                        ZW_Ctx.drawImage(tempImage, visibleX, visibleY, visibleW, visibleH, imgX, imgY, imgW, imgH)
                                                }

                                                ZW_Ctx.restore();

                                                resolve({
                                                        code: 0,
                                                })

                                        }
                                }
                        })
                })

        },

        async onSaveClick() {
                wx.showLoading({
                        title: "加载中",
                });
                app.saveTrack(`R5-发表成功-保存本地`);
                // await this.drawCanvas();

                wx.saveImageToPhotosAlbum({
                        filePath: this.data.shotImageUrl,
                        success: data => {
                                wx.showToast({
                                        title: '保存成功',
                                })
                                wx.hideLoading();
                        },
                        fail: err => {
                                wx.showToast({
                                        icon: "none",
                                        title: '保存失败',
                                })
                                wx.hideLoading();
                        }
                })
        },

        onShareAppMessage(object) {
                if(object.from == "menu") {
                        return {
                                title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                                path: `/pages/index/index?inChannel=commonShare`,
                                imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                        }
                }

                app.saveTrack(`R5-发表成功-分享`);
                return {
                        title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                        path: `/pages/index/index?toPage=showStory&storyId=${this.data.inStoryId}`,
                        imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                }
        },

        async shotCanvasImage(inType) {
                let _self = this;
                console.log('shot');
                return new Promise((resolve, reject) => {

                        setTimeout(() => {
                                wx.canvasToTempFilePath({
                                        canvas: ZW_Canvas,
                                        success: (res) => {
                                                console.log("shotCanvasImage === ", res)
                                                _self.setData({
                                                        shotImageUrl: res.tempFilePath
                                                })
                                                resolve({
                                                        code: 0,
                                                })
                                        },
                                        fail: err => {
                                                console.log("shotCanvasImage === err ", err)
                                        }
                                })
                        }, 20);


                })
        },

        goBack() {
                wx.navigateBack();
        }
})